<?php

/**
 * @Author: kendy
 * @Date:   2020-02-11 10:26:45
 * @Last Modified by:   jiayanting
 * @Last Modified time: 2020-04-24 11:37:59
 */

namespace app\api\model;

use think\Controller;
use think\Model;
use think\Db;
use think\Queue;

class Payments extends Model
{
    /**
     * [getFieldByType 根据类型获取字段]
     * @Author   kendy
     * @DateTime 2020-02-11T13:01:53+0800
     * @param    [type]                   $payType [支付类型 1酒店，2景点，3跟团]
     * @return   [type]                            []
     */
    public function getFieldByType($orderType)
    {
        if ($orderType == 1) {
            return ['hotel_order', 'uid', 'hotel', 'hotel_id', 'hotel_id', 'hotel_name'];
        }
        if ($orderType == 2) {
            return ['tour_order', 'user_id', 'tours', 'tour_id', 'tour_id', 'tour_name'];
        }
        if ($orderType == 3) {
            return ['gtour_order', 'user_id', 'group_tour', 'id', 'gtour_id', 'gtour_title'];
        }
    }

    /**
     * [complatePay 完成支付订单]
     * @Author   kendy
     * @DateTime 2020-02-11T10:27:31+0800
     * @param    [type]                   $obj [支付成功返回对象]
     * @return   [type]                        [description]
     */
    public function complatePay($obj)
    {
        //$obj
        $tradeNo = $obj['trade_no']; //在线支付交易流水
        $orderSn = $obj['out_trade_no']; //商户订单号
        $payPrice = $obj['total_amount'];//支付的金额
        $orderType = $obj['order_type'];//订单类型 订单类型 1酒店，2景点，3跟团
        $payType = $obj['pay_type'];//支付类型1支付宝，2微信
        $userId = $obj['uid'];
        $orderTable = $this->getFieldByType($orderType);
        $where = [$orderTable[1] => $userId, 'order_sn' => $orderSn, "order_status" => 0, "is_pay" => 2, "order_price" => [">", 0]];
        $totalPrice = Db::name($orderTable[0])->where($where)->value('order_price');
        if ($totalPrice < $payPrice) {
            return apiReturn('400', '支付金额不正确', 0);
        }
        Db::startTrans();
        try {
            $data = array();
            $data["is_pay"] = 1;
            $data["trade_no"] = $tradeNo;
            $data["pay_type"] = $payType;
            $data["order_status"] = 1;
            if ($orderType == 1) {
                $data["order_status"] = 6;
            }
            $rs = Db::name($orderTable[0])->where($where)->update($data);
            $orderInfo = Db::name($orderTable[0])
                ->alias("o")
                ->join('' . $orderTable[2] . ' shop ', 'shop.' . $orderTable[3] . '=o.' . $orderTable[4] . '', 'inner')
                ->where(["o.order_sn" => $orderSn])
                ->find();
            if ($payPrice > 0 && false != $rs) {
                $orderId = $orderInfo["order_id"];
                //新增订单日志
                $logOrder = [];
                $logOrder['order_id'] = $orderId;
                $logOrder['order_status'] = $data["order_status"];
                $logOrder['log_content'] = "订单已支付,下单成功";
                $logOrder['user_id'] = $userId;
                $logOrder['create_time'] = time();
                $logOrder['order_type'] = $orderType;
                Db::name('log_orders')->insert($logOrder);
                //创建一条支付流水记录
                $lm = [];
                $lm['target_type'] = 0;
                $lm['target_id'] = $userId;
                $lm['data_id'] = $orderId;
                $lm['data_src'] = 1;
                $lm['remark'] = '交易订单【' . $orderInfo['order_sn'] . '】支付¥' . $payPrice;
                $lm['money_type'] = 0;
                $lm['money'] = $payPrice;
                $lm['money_type'] = 0;
                $lm['pay_type'] = $payType;
                $lm['create_time'] = date('Y-m-d H:i:s');
                Db::name('log_moneys')->insert($lm);
                //增加未结算的订单佣金
                $commissionFee = 0;
                if ($orderInfo['commission_rate'] > 0) {
                    if ($orderType == 1) {
                        $commissionFee = $orderInfo["total_price"] * $orderInfo['room_amount'] * $orderInfo['commission_rate'] / 1000;
                    } else {
                        $commissionFee = $orderInfo["order_price"] * $orderInfo['commission_rate'] / 1000;
                    }
                }

                //未结算单的订单佣金
                //发送一条商家信息
                if ($orderType == 1) {
                    $jobHandlerClassName = 'app\api\job\Order';
                    $jobQueueName = 'Hello';
                    $jobData = [ 
                      'uid'=>2, 
                      'order_id'=>$orderId,  
                    ]; 
                   $isPushed = Queue::later(1800,$jobHandlerClassName , $jobData , $jobQueueName);
                   //发送用户短信   
                    $userfasong = [
                        '1' => $orderInfo['hotel_name'],
                        '2' => $orderInfo['room_name'],
                        '3' => $orderInfo['order_sn']
                    ];
                     sendJsmsMessage($orderInfo['tel'], 178086, $userfasong);
                     //发送商家通知
                     $fasong = [
                        '1' => $orderInfo[$orderTable[5]],
                        '2' => $orderInfo['order_sn']
                    ]; 
                    $templateId = 174980;
                    $orderInfo['tel'] = $orderInfo['send_tel'];
                    Db::name($orderTable[2])->where($orderTable[3], $orderInfo[$orderTable[3]])->setInc('no_settled_order_fee', $commissionFee);
                }
                if ($orderType == 2) { //景点
                    /*1，订单号
                    2，景点名称
                    3，门票的失效期*/
                    $fasong = [
                        '1' => $orderInfo['order_sn'],
                        '2' => $orderInfo[$orderTable[5]],
                        '3' => date('Y-m-d', $orderInfo['ticket_date'])
                    ];
                    $templateId = 174985;
                    Db::name($orderTable[2])->where($orderTable[3], $orderInfo[$orderTable[3]])->setInc('no_settled_order_fee', $commissionFee);
                }
                if ($orderType == 3) {// 3是跟团
                    /*1订单号
                      2跟团游产品
                      3旅行社名称
                      4电话*/
                    $teamInfo = Db::name("team")->where("team_id", $orderInfo['team_id'])->find();//->setInc('no_settled_order_fee',$commissionFee);
                    Db::name("team")->where("team_id", $orderInfo['team_id'])->update(['no_settled_order_fee' => $teamInfo['no_settled_order_fee'] + $commissionFee]);
                    $fasong = [
                        '1' => $orderInfo['order_sn'],
                        '2' => $orderInfo[$orderTable[5]],
                        '3' => $teamInfo['team_name'],
                        '4' => $teamInfo['team_phone']
                    ];
                    $templateId = 175239;
                }
                if (preg_match("/^1[345678]{1}\d{9}$/", $orderInfo['tel'])) {
                    sendJsmsMessage($orderInfo['tel'], $templateId, $fasong);
                }

            }
            Db::commit();
            return apiReturn('200', '支付成功', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return apiReturn('400', '操作失败', $e->getMessage());
        }
    }

    /**
     * [complatePay 完成捡漏支付订单]
     * @Author   kendy
     * @DateTime 2020-02-11T10:27:31+0800
     * @param    [type]                   $obj [支付成功返回对象]
     * @return   [type]                        [description]
     */
    public function complateJlouPay($obj)
    {
        //$obj
        $tradeNo = $obj['trade_no']; //在线支付交易流水
        $orderSn = $obj['out_trade_no']; //商户订单号
        $payPrice = $obj['total_amount'];//支付的金额
        $orderType = $obj['order_type'];//订单类型 订单类型 1酒店，2景点，3跟团
        $payType = $obj['pay_type'];//支付类型1支付宝，2微信
        $userId = $obj['uid'];
        if ($payType > 0) {
            $cnt = Db::name("jlou_order")
                ->where(['pay_type' => $payType, 'uid' => $userId, "trade_no" => $tradeNo, 'order_sn' => $orderSn])
                ->count();
            if ($cnt > 0) {
                return apiReturn('400', '订单已支付', 0);
            }
        }
        $where = ['uid' => $userId, 'order_sn' => $orderSn, "order_status" => 0, "order_price" => [">", 0]];
        $orderInfo = Db::name("jlou_order")
            ->alias("o")
            ->join('jlou_goods goods', 'goods.id=o.goods_id', 'inner')
            ->where(["o.order_sn" => $orderSn])
            ->find();

        if (empty($orderInfo)) return apiReturn('400', '无此订单信息', 0);
        Db::startTrans();
        try { 
            $data = array();
            //特别商品参与码查看同一期的
            $orderGood = Db::name("jlou_order")
                ->where('goods_id', $orderInfo['goods_id'])
                ->order('order_code desc')
                ->limit(1)
                ->find();
            if($orderInfo['is_real'] == 1){  
               if (!empty($orderGood['cancel_code'])){ $code =  (int)substr($orderGood['cancel_code'],4,11);  $data['cancel_code'] = 'YSLY'.($code + 1); }
               else{ $data['cancel_code']  = 'YSLY1000000';}
                 
            }   
            if (!empty($orderGood['order_code'])) $orderCode = (int)$orderGood['order_code'] + 1;
            else  $orderCode = 10000000;
            $data["order_code"] = $orderCode;
            $data["trade_no"] = $tradeNo;
            $data["pay_type"] = $payType;
            $data["order_status"] = 1;
            $rs = Db::name("jlou_order")->where($where)->update($data);

            if ($payPrice > 0 && false != $rs) {
                $orderId = $orderInfo["order_id"];
                //新增订单日志
                $logOrder = [];
                $logOrder['order_id'] = $orderId;
                $logOrder['order_status'] = $data["order_status"];
                $logOrder['log_content'] = "订单已支付,下单成功";
                $logOrder['user_id'] = $userId;
                $logOrder['create_time'] = time();
                $logOrder['order_type'] = $orderType;
                Db::name('log_orders')->insert($logOrder);
                //创建一条支付流水记录
                $lm = [];
                $lm['target_type'] = 0;
                $lm['target_id'] = $userId;
                $lm['data_id'] = $orderId;
                $lm['data_src'] = 1;
                $lm['remark'] = '交易订单【' . $orderInfo['order_sn'] . '】支付¥' . $payPrice;
                $lm['money_type'] = 0;
                $lm['money'] = $payPrice;
                $lm['money_type'] = 0;
                $lm['pay_type'] = $payType;
                $lm['create_time'] = date('Y-m-d H:i:s');
                Db::name('log_moneys')->insert($lm);
                //修改总销售量
                Db::name('jlou_goods')->where('id', $orderInfo['goods_id'])->setInc('number', 1);
            }
            Db::commit();
            return apiReturn('200', '支付成功', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return apiReturn('400', '操作失败', $e->getMessage());
        }
    }

    /**
     * [complateBargainPay 砍价支付回调方法]
     * @Author   kendy
     * @DateTime 2020-03-10T08:44:45+0800
     * @return   [type]                   [description]
     */
    public function complateBargainPay($obj)
    {
        $tradeNo = $obj['trade_no']; //在线支付交易流水
        $orderSn = $obj['out_trade_no']; //商户订单号
        $payPrice = $obj['total_amount'];//支付的金额
        $orderType = $obj['order_type'];//订单类型 订单类型 1酒店，2景点，3跟团
        $payType = $obj['pay_type'];//支付类型0为砍价 1支付宝，2微信
        $userId = $obj['uid'];
        $where = ['uid' => $userId, 'order_sn' => $orderSn, "order_status" => 0, "order_price" => [">", 0]];
        $orderInfo = Db::name('bargain_order')
            ->where($where)
            ->find();
        if ($orderInfo['order_price'] != $payPrice) {
            return apiReturn('400', '支付金额不正确', 0);
        }
        Db::startTrans();
        try {
            $data = array();
            $data["trade_no"] = $tradeNo;
            $data["pay_type"] = $payType;
            $data["order_status"] = 1;
            $rs = Db::name("bargain_order")->where($where)->update($data);
            if (false != $rs) {
                $orderId = $orderInfo["order_id"];
                //新增订单日志
                $logOrder = [];
                $logOrder['order_id'] = $orderId;
                $logOrder['order_status'] = $data["order_status"];
                $logOrder['log_content'] = "订单已支付,下单成功";
                $logOrder['user_id'] = $userId;
                $logOrder['create_time'] = time();
                $logOrder['order_type'] = $orderType;
                Db::name('log_orders')->insert($logOrder);
                //创建一条支付流水记录
                $lm = [];
                $lm['target_type'] = 0;
                $lm['target_id'] = $userId;
                $lm['data_id'] = $orderId;
                $lm['data_src'] = 1;
                $lm['remark'] = '交易订单【' . $orderInfo['order_sn'] . '】支付¥' . $payPrice;
                $lm['money_type'] = 0;
                $lm['money'] = $payPrice;
                $lm['money_type'] = 0;
                $lm['pay_type'] = $payType;
                $lm['create_time'] = date('Y-m-d H:i:s');
                Db::name('log_moneys')->insert($lm);
            }
            Db::commit();
            return apiReturn('200', '支付成功', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return apiReturn('400', $e->getMessage(), 0);
        }
    }
    /**
     * [complateBargainPay 投票支付回调方法]
     * @Author   kendy
     * @DateTime 2020-03-10T08:44:45+0800
     * @return   [type]                   [description]
     */
    public function complateVotePay($obj){
        $tradeNo = $obj['trade_no']; //在线支付交易流水
        $orderSn = $obj['out_trade_no']; //商户订单号
        $payPrice = $obj['total_amount'];//支付的金额
        $orderType = $obj['order_type'];//订单类型 订单类型 1酒店，2景点，3跟团
        $payType = $obj['pay_type'];//支付类型0为砍价 1支付宝，2微信
        $userId = $obj['uid'];
        $where = ['uid' => $userId, 'order_sn' => $orderSn, "order_status" => 0];
        $orderInfo = Db::name('vote_order')
            ->where($where)
            ->find();
        if ($orderInfo['order_price'] != $payPrice) {
            return apiReturn('400', '支付金额不正确');
        }
        Db::startTrans();
        //处理 加金币数
        Db::name('vote_option')->where('id',$orderInfo['option_id'])->setInc('vote_number',$orderInfo['vote_num']);
        try {
            $data = array();
            $data["trade_no"] = $tradeNo;
            $data["pay_type"] = $payType;
            $data["order_status"] = 1;
            $rs = Db::name("vote_order")->where($where)->update($data);
            if (false != $rs) {
                $orderId = $orderInfo["order_id"];
                //新增订单日志
                $logOrder = [];
                $logOrder['order_id'] = $orderId;
                $logOrder['order_status'] = $data["order_status"];
                $logOrder['log_content'] = "订单已支付,下单成功";
                $logOrder['user_id'] = $userId;
                $logOrder['create_time'] = time();
                $logOrder['order_type'] = $orderType;
                Db::name('log_orders')->insert($logOrder);
                //创建一条支付流水记录
                $lm = [];
                $lm['target_type'] = 0;
                $lm['target_id'] = $userId;
                $lm['data_id'] = $orderId;
                $lm['data_src'] = 1;
                $lm['remark'] = '交易订单【' . $orderInfo['order_sn'] . '】支付¥' . $payPrice;
                $lm['money_type'] = 0;
                $lm['money'] = $payPrice;
                $lm['money_type'] = 0;
                $lm['pay_type'] = $payType;
                $lm['create_time'] = date('Y-m-d H:i:s');
                Db::name('log_moneys')->insert($lm);

            }
            Db::commit();
            return apiReturn('200', '支付成功', $orderInfo['vote_num']);
        } catch (\Exception $e) {
            Db::rollback();
            return apiReturn('400', $e->getMessage(), 0);
        }
    }

}